import { native as format } from '../format/index'
import { getLocation } from '../utils/path'
import { _GT, _ST } from '../utils/storage'

const _hostSdk = {
	setStatFun() {},
	partyCall() {},
}

const key = 'NativePlugin-duration'
const getTime = () => _GT(key, Date.now())
const setTime = value => _ST(key, value)
let time = getTime()
let _time = 0
let diff = 0
const updateTime = () => {
	_time = Date.now()
	diff = _time - time
	time = _time

	setTime(time)

	return true
}

/**
 * @method NativePlugin
 * @description 原生App插件，提供h5上报、页面end上报、h5跳客户端上报
 * @param {Object} hostSdk host-sdk依赖，需传入
 * @param {Array} pathFilter 需要过滤触发页面end的页面，例如在app首页tab栏的webview页面
 */
export default class NativePlugin {
	constructor(hostSdk = _hostSdk, { pathFilter = [], ...options } = {}) {
		this.hostSdk = hostSdk
		this.pathFilter = pathFilter
		this.options = options
	}

	apply = stat => {
		console.log('Stat use: NativePlugin')

		stat.pipe(format)

		stat.setOptions({
			report: (data, ...arg) => this.hostSdk.partyCall('stat', JSON.stringify(data), ...arg)
		})

		// 页面end ------------------------------------------------------------------------------------------------------------------------
		const getDiffData = (isSdk = false, _diff) => ({ pageName: stat.getCurrentData()[0][isSdk ? 'pageName' : 'parentPage'], duration: _diff || diff })

		// 客户端生命周期 onPause ，在webview被遮盖或销毁时执行
		this.hostSdk.addPause(() => {
			if (this.pathFilter.find(item => getLocation().pathname.indexOf(item) > -1)) return
			
			const params = updateTime() && getDiffData(true)

			if (params.duration > 500) this.hostSdk.partyCall('uploadPageEndStatistics', params)
		})
		
		// 设置从客户端跳转到页面时 获取页面数据的方法
		this.hostSdk.setStatFun(() => {
			updateTime() && this.hostSdk.partyCall('uploadPageEndStatistics', getDiffData(true))

			return stat.getCurrentData()
		})

		// 有路由的页面停留时间
		if (stat.route) {
			const uploadPageEnd = chain => chain.length > 1 && updateTime() && this.hostSdk.partyCall('uploadPageEndStatistics', getDiffData())

			// 补偿
			uploadPageEnd(stat.route.getOwnChain())
			stat.route.afterEach(to => uploadPageEnd(to.chain))
		}
		// ---------------------------------------------------------------------------------------------------------------------------------
	}
}